package com.zhongpengcheng.blog.config;

import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.zhongpengcheng.blog.util.TokenUtils;
import com.zhongpengcheng.blog.properties.JWTProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * JWT配置
 * note: 1.记录变更 by zhongpengcheng
 *
 * @author zhongpengcheng
 * @date 2021/08/26 12:43
 **/
@Slf4j
@Configuration
@EnableConfigurationProperties(JWTProperties.class)
public class JWTConfiguration {
    private final JWTProperties property;

    @Autowired
    public JWTConfiguration(JWTProperties jwtProperties) {
        this.property = jwtProperties;
    }

    @Bean
    public JWTSigner accessSigner() {
        return JWTSignerUtil.createSigner(property.getAlgorithm(), property.getAccessSecret().getBytes());
    }

    @Bean
    public JWTSigner refreshSigner() {
        return JWTSignerUtil.createSigner(property.getAlgorithm(), property.getRefreshSecret().getBytes());
    }

    @PostConstruct
    public void init() {
        log.info("initializing JWT configuration");
        TokenUtils.setProperties(property);
        log.info("initializing access JWT signer");
        TokenUtils.setAccessSigner(accessSigner());
        log.info("initializing refresh JWT signer");
        TokenUtils.setRefreshSigner(refreshSigner());
    }
}
